package com.demo.service;

import java.util.Date;
import java.util.List;

import com.demo.common.model.Book;
import com.demo.common.model.ExchangeItem;
import com.demo.common.model.ExchangeTrade;
import com.demo.common.model.OrderItem;
import com.demo.common.model.SecondTrade;
import com.demo.common.model.User;
import com.demo.constants.Constants;
import com.demo.constants.GeneralUtil;
import com.jfinal.plugin.activerecord.Page;

public class TradeService {

	private static final SecondTrade dao = new SecondTrade().dao();

	private static final ExchangeItem exdao = new ExchangeItem().dao();

	public void sold(User suser, SecondTrade trade) {
		OrderItem orderItem = OrderItem.dao.findById(trade.getOrderItemId());
		String id = "S" + GeneralUtil.getBizNo() + GeneralUtil.getCode(3, 0);
		trade.setId(id);
		trade.setBookId(orderItem.getBookId());
		trade.setUserId(suser.getId());
		trade.setPrice(orderItem.getPrice());
		trade.setNum(orderItem.getNum());
		trade.setCreateTime(new Date());
		trade.setTotal(orderItem.getTotal());
		trade.setStatus(Constants.trade_status_auditing);
		trade.save();

		orderItem.setStatus(Constants.order_item_status_sold);
		orderItem.update();
	}

	public Page<SecondTrade> getSoldList(int pageNumber, int pageSize,
			User suser, int tradeType) {
		Page<SecondTrade> page = null;
		if (tradeType == Constants.trade_type_buy) {
			page = dao
					.paginate(
							pageNumber,
							pageSize,
							"select *",
							"from second_trade where buyer_id=? order by create_time desc",
							suser.getId());
		} else if (tradeType == Constants.trade_type_sold) {
			page = dao
					.paginate(
							pageNumber,
							pageSize,
							"select *",
							"from second_trade where user_id=? order by create_time desc",
							suser.getId());
		} else if (tradeType == Constants.trade_type_auditing) {
			page = dao
					.paginate(
							pageNumber,
							pageSize,
							"select *",
							"from second_trade where status=? order by create_time desc",
							Constants.trade_status_auditing);
		} else {
			page = dao
					.paginate(
							pageNumber,
							pageSize,
							"select *",
							"from second_trade where status=? order by create_time desc",
							Constants.trade_status_trading);
		}

		List<SecondTrade> list = page.getList();
		for (SecondTrade secondTrade : list) {
			secondTrade.setBook(Book.dao.findById(secondTrade.getBookId()));
			secondTrade.setUser(User.dao.findById(secondTrade.getUserId()));
		}

		return page;
	}

	public SecondTrade getSoldDetail(String sid) {
		SecondTrade secondTrade = dao.findById(sid);
		secondTrade.setBook(Book.dao.findById(secondTrade.getBookId()));
		return secondTrade;
	}

	public void dosoldaudit(String id, Integer status, User suser) {
		status = Constants.trade_status_trading == status ? Constants.trade_status_trading
				: Constants.trade_status_reject;
		SecondTrade secondTrade = dao.findById(id);
		secondTrade.setStatus(status);
		secondTrade.update();
	}

	public String buySold(SecondTrade trade, User suser) {
		SecondTrade trade2 = dao.findById(trade.getId());
		User user = User.dao.findById(suser.getId());
		if (user.getBlance() < trade2.getSoldTotal()) {
			return Constants.error_code_blance_insufficient;
		}
		user.setBlance(user.getBlance() - trade2.getSoldTotal());
		user.update();

		trade2.setBuyerId(suser.getId());
		trade2.setBuyerName(trade.getBuyerName());
		trade2.setBuyerMobile(trade.getBuyerMobile());
		trade2.setBuyerAddress(trade.getBuyerAddress());
		trade2.setStatus(Constants.trade_status_delivery);
		trade2.update();
		return Constants.error_code_success;
	}

	public String delivery(String orderId, User suser) {
		if (orderId.startsWith("S")) {
			SecondTrade trade = dao.findById(orderId);
			trade.setStatus(Constants.trade_status_receiving);
			trade.update();
		} else {
			ExchangeTrade eTrade = ExchangeTrade.dao.findById(orderId);
			ExchangeItem exchangeItem = null;
			if (eTrade.getUserId() == suser.getId()) {
				exchangeItem = ExchangeItem.dao.findById(eTrade
						.getUserExchangeItemId());
			} else if (eTrade.getBuyerId() == suser.getId()) {
				exchangeItem = ExchangeItem.dao.findById(eTrade
						.getBuyerExchangeItemId());
			}
			if (exchangeItem != null) {
				exchangeItem.setStatus(Constants.trade_status_receiving);
				exchangeItem.update();
			}
		}
		return Constants.error_code_success;
	}

	public String received(String orderId, User suser) {
		if (orderId.startsWith("S")) {
			SecondTrade trade = dao.findById(orderId);
			trade.setStatus(Constants.trade_status_success);
			trade.update();
		} else {
			ExchangeTrade eTrade = ExchangeTrade.dao.findById(orderId);
			ExchangeItem userExchangeItem = ExchangeItem.dao.findById(eTrade
					.getUserExchangeItemId());
			ExchangeItem buyerExchangeItem = ExchangeItem.dao.findById(eTrade
					.getBuyerExchangeItemId());
			if (eTrade.getBuyerId() == suser.getId()) {
				userExchangeItem.setStatus(Constants.trade_status_success);
				userExchangeItem.update();
				if (buyerExchangeItem.getStatus() == Constants.trade_status_success) {
					eTrade.setStatus(Constants.trade_status_success);
					eTrade.update();
				}

			} else if (eTrade.getUserId() == suser.getId()) {
				buyerExchangeItem.setStatus(Constants.trade_status_success);
				buyerExchangeItem.update();
				if (userExchangeItem.getStatus() == Constants.trade_status_success) {
					eTrade.setStatus(Constants.trade_status_success);
					eTrade.update();
				}
			}
		}
		return Constants.error_code_success;
	}

	public String close(String orderId, User suser) {
		if (orderId.startsWith("S")) {
			SecondTrade trade = dao.findById(orderId);
			if (trade.getUserId() == suser.getId()) {
				trade.setStatus(Constants.trade_status_close);
				trade.update();
			}
		} else {
			ExchangeTrade eTrade = ExchangeTrade.dao.findById(orderId);
			if (eTrade.getUserId() == suser.getId()) {
				eTrade.setStatus(Constants.trade_status_close);
				ExchangeItem exchangeItem = exdao.findById(eTrade
						.getUserExchangeItemId());
				exchangeItem.setStatus(Constants.trade_status_close);
				exchangeItem.update();
				eTrade.update();
			}
		}
		return Constants.error_code_success;
	}

	public Page<ExchangeItem> getExchangeList(int pageNumber, int pageSize,
			User suser, int tradeType) {
		Page<ExchangeItem> page = null;
		if (tradeType == Constants.trade_type_buy) {
			page = exdao
					.paginate(
							pageNumber,
							pageSize,
							"select i.*,e.id tradeId",
							"FROM   exchange_trade e,exchange_item i  where e.buyer_exchange_item_id = i.id and e.buyer_id=? order by i.id desc",
							suser.getId());
		} else if (tradeType == Constants.trade_type_sold) {
			page = exdao
					.paginate(
							pageNumber,
							pageSize,
							"select i.*,e.id tradeId",
							"FROM   exchange_trade e,exchange_item i  where e.user_exchange_item_id = i.id and e.user_id=? order by i.id desc",
							suser.getId());
		} else if (tradeType == Constants.trade_type_auditing) {
			page = exdao
					.paginate(
							pageNumber,
							pageSize,
							"select i.*,e.id tradeId",
							"FROM   exchange_trade e,exchange_item i  where e.user_exchange_item_id = i.id and e.status=? order by e.create_time desc",
							Constants.trade_status_auditing);
		} else {
			page = exdao
					.paginate(
							pageNumber,
							pageSize,
							"select i.*,e.id tradeId",
							"FROM   exchange_trade e,exchange_item i  where e.user_exchange_item_id = i.id and i.status=? order by i.id  desc",
							Constants.trade_status_trading);
		}

		List<ExchangeItem> list = page.getList();
		for (ExchangeItem exchangeItem : list) {
			exchangeItem.setBook(Book.dao.findById(exchangeItem.getBookId()));
			ExchangeTrade trade = ExchangeTrade.dao.findById(exchangeItem
					.getStr("tradeId"));
			exchangeItem.setTrade(trade);
			if (exchangeItem.getId() == trade.getUserExchangeItemId()) {
				trade.setBuyerTrade(exdao.findById(trade
						.getBuyerExchangeItemId()));
			} else {
				trade.setUserTrade(exdao.findById(trade.getUserExchangeItemId()));
			}
		}

		return page;
	}

	public void exchange(User suser, ExchangeItem eitem) {
		ExchangeTrade trade = new ExchangeTrade();
		String id = "E" + GeneralUtil.getBizNo() + GeneralUtil.getCode(3, 0);
		trade.setId(id);
		trade.setUserId(suser.getId());
		trade.setCreateTime(new Date());
		trade.setStatus(Constants.trade_status_auditing);

		OrderItem orderItem = OrderItem.dao.findById(eitem.getOrderItemId());
		eitem.setBookId(orderItem.getBookId());
		eitem.setPrice(orderItem.getPrice());
		eitem.setNum(orderItem.getNum());
		eitem.setTotal(orderItem.getTotal());
		eitem.setPriceType(orderItem.getPriceType());
		eitem.save();

		trade.setUserExchangeItemId(eitem.getId());
		trade.save();

		orderItem.setStatus(Constants.order_item_status_exchange);
		orderItem.update();
	}

	public void doexchaudit(String id, Integer status, User suser) {
		status = Constants.trade_status_trading == status ? Constants.trade_status_trading
				: Constants.trade_status_reject;

		ExchangeTrade trade = ExchangeTrade.dao.findById(id);
		trade.setStatus(status);
		trade.update();
		if (Constants.trade_status_trading == status) {
			exdao.findById(trade.getUserExchangeItemId())
					.setStatus(Constants.trade_status_trading).update();
		}

	}

	public ExchangeTrade getExchDetail(String sid) {
		ExchangeTrade trade = ExchangeTrade.dao.findById(sid);
		ExchangeItem exchangeItem = exdao.findById(trade
				.getUserExchangeItemId());
		exchangeItem.setBook(Book.dao.findById(exchangeItem.getBookId()));
		trade.setUserTrade(exchangeItem);
		if (trade.getBuyerExchangeItemId() != null) {
			exchangeItem = exdao.findById(trade.getBuyerExchangeItemId());
			exchangeItem.setBook(Book.dao.findById(exchangeItem.getBookId()));
			trade.setBuyerTrade(exchangeItem);
		}
		return trade;
	}

	public List<OrderItem> getExchOrderItem(String sid, User suser) {
		ExchangeTrade trade = ExchangeTrade.dao.findById(sid);
		ExchangeItem exchangeItem = exdao.findById(trade
				.getUserExchangeItemId());
		List<OrderItem> list = OrderItem.dao
				.find("select oi.* from `order` o,order_item oi where o.id = oi.order_id and o.status=4 and oi.status=1 and o.user_id= ? and oi.price_type=? and oi.num >= ?",
						suser.getId(), exchangeItem.getPriceType(),
						exchangeItem.getNum());
		for (OrderItem item : list) {
			item.setBook(Book.dao.findById(item.getBookId()));
		}
		return list;
	}

	public String buyexch(String tradeId, ExchangeItem eItem, User suser) {
		ExchangeTrade trade = ExchangeTrade.dao.findById(tradeId);

		ExchangeItem exchangeItem = exdao.findById(trade
				.getUserExchangeItemId());
		OrderItem orderItem = OrderItem.dao.findById(eItem.getOrderItemId());
		eItem.setBookId(orderItem.getBookId());
		eItem.setNum(exchangeItem.getNum());
		eItem.setPrice(orderItem.getPrice());
		eItem.setPriceType(orderItem.getPriceType());
		eItem.setTotal(orderItem.getPrice() * exchangeItem.getNum());
		eItem.setStatus(Constants.trade_status_delivery);
		eItem.save();

		exchangeItem.setStatus(Constants.trade_status_delivery);
		exchangeItem.update();

		trade.setBuyerExchangeItemId(eItem.getId());
		trade.setBuyerId(suser.getId());
		trade.update();

		return Constants.error_code_success;
	}
}
